package logic

import (
	"bytes"
	"context"
	"encoding/json"
	"everyone/C/rpc_C/model/es"
	"log"

	"everyone/C/rpc_C/everyone"
	"everyone/C/rpc_C/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ESsearchLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewESsearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ESsearchLogic {
	return &ESsearchLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ESsearchLogic) ESsearch(in *everyone.ESsearchRequest) (*everyone.GoodsListResponse, error) {
	// todo: add your logic here and delete this line
	var buf bytes.Buffer
	query := map[string]interface{}{}
	if in.Keyword != "" {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match": map[string]interface{}{
					"goodsTitle": in.Keyword,
				},
			},
		}
	} else {
		query = map[string]interface{}{
			"query": map[string]interface{}{
				"match_All": map[string]interface{}{},
			},
		}
	}

	if err := json.NewEncoder(&buf).Encode(query); err != nil {
		log.Fatalf("Error encoding query: %s", err)
	}

	// Perform the search request.
	res, err := es.Es.Search(
		es.Es.Search.WithContext(context.Background()),
		es.Es.Search.WithIndex("test"),
		es.Es.Search.WithBody(&buf),
		es.Es.Search.WithTrackTotalHits(true),
		es.Es.Search.WithPretty(),
	)
	if err != nil {
		log.Fatalf("Error getting response: %s", err)
	}
	defer res.Body.Close()

	if res.IsError() {
		var e map[string]interface{}
		if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
			log.Fatalf("Error parsing the response body: %s", err)
		} else {
			// Print the response status and error information.
			log.Fatalf("[%s] %s: %s",
				res.Status(),
				e["error"].(map[string]interface{})["type"],
				e["error"].(map[string]interface{})["reason"],
			)
		}
	}
	var r map[string]interface{}
	json.NewDecoder(res.Body).Decode(&r)
	/*	for _, hit := range r["hits"].(map[string]interface{})["hits"].([]interface{}) {
		source:=hit.(map[string]interface{})["_source"]).([]interface{})
		}*/

	return &everyone.GoodsListResponse{}, nil
}
